//header("content-type:www-forms-unicodelend");
var str;
var createBy = localStorage.getItem("username");
var dataPacketFileName = localStorage.getItem('dataPacketFileName');
var parentNodes = [];
// 树结构基本配置
var setting = {
  data: {
    simpleData: {
      enable: true,
      idKey: "sid",
      pIdKey: "pid",
      rootPId: 0
    },
    key: {
      name: 'nodename'
    }
  },
  edit: {
    enable: false,
    showRenameBtn: false,
    renameTitle: "编辑节点名称",
    removeTitle: "删除节点"
  },
  callback: {
    onClick: function (event, treeId, treeNode) {
      console.log(event);
      console.log(treeId);
      console.log(treeNode, 'treeNode节点', this);
      console.log(treeNode.htmlName);


      var element = document.getElementById(treeNode.tId);
      if (treeNode.htmlName) {
        element.classList.add('_isDmt');
      } else {
        element.classList.add('_isDmf');
      }

      //     --------------------------------------  添加导航栏
      // 获取 zTree 对象
      // var zTree = $("#tree");
      const zTree = $.fn.zTree.getZTreeObj("tree");

      // 获取所有节点数据
      const nodes = zTree.getNodes();
      console.log(nodes, '获取所有节点数据');
      // 获取当前节点的父级组成的数组
      parentNodes = [];
      let currentNode = treeNode;

      // 遍历父级节点，直到根节点
      while (currentNode && currentNode.getParentNode) {
        currentNode = currentNode.getParentNode(); // 获取父节点
        if (currentNode) {
          parentNodes.unshift(currentNode); // 添加到数组开头
        }
      }
      var dataPacketFileName = localStorage.getItem('dataPacketFileName');
      parentNodes.push(treeNode)
      console.log(parentNodes, "父级节点数组", $("#nav_box"));
      let parentNodesStr = `<span class="_span" data-sid="" data-htmlname="">${dataPacketFileName}</span><div class="icon_jiant"></div>`;
      parentNodesStr += parentNodes.map(node => `<span class="${node.htmlName ? 'isDm _span' : '_span'}" data-sid="${node.sid}" data-htmlname="${node.htmlName}">${node.nodename}</span>`).join('<div class="icon_jiant"></div>');
      $("#nav_box").html(parentNodesStr);

      var str = treeNode.htmlName + '';
      localStorage.setItem('dataModuleFileName', treeNode.htmlName);
      localStorage.setItem('dataModuleName', treeNode.nodename);
      if (str.trim() != '') {
        $('#myFrame').attr('src', treeNode.htmlName + '.html');
        $("#zy").find("a").attr("href", treeNode.htmlName + '.html');
      } else {
        $('#myFrame').attr('src', '');
        $("#zy").find("a").attr("href", '');
      }

      if (treeNode.htmlName) {
        localStorage.setItem('dataModuleFileName', treeNode.htmlName);
        
        $.ajax({
          type: "POST",
          url: '/ietm/history/addOrUpdate',
          data: {
            "dataPacketFileName": dataPacketFileName,
            "dataModuleFileName": treeNode.htmlName,
            "dataModuleName": treeNode.nodename,
            "createBy": localStorage.getItem("username"),
          },
          dataType: "JSON",
          success: function (res) {
            if (res.code == 200) {
              console.log(res);

            } else {
              if (res.msg.includes("未登录")) {
                layer.msg('用户未登录!');
                setTimeout(function () {
                  parent.wlogout()
                }, 1500);
                return false;
              } else {
                layer.msg('请求失败 !');
              }
            }
          }, error: function (res) {
            layer.msg('请求失败 !');
          }
        })
      }

    }
  }
}


function checkP(id) {
  var array = [];
  var arrayJSON = [];
  array = JSON.parse(JSON.stringify(zNodes));

  for (var i = 0; i < array.length; i++) {

    var titleStr = array[i].pid;
    ////console.log(titleStr);
    if (titleStr == id) {
      return true;
    }
  }
  return false;
}

function checkN(name) {
  console.log("in to checkN:" + name);
  console.log(zNodes[name]);
  var array = [];
  var arrayJSON = [];
  array = JSON.parse(JSON.stringify(zNodes));
  var id = 0;
  for (var i = 0; i < array.length; i++) {

    var titleStr = array[i].link;
    console.log(titleStr);
    if (titleStr == name) {
      id = array[i].id;
      console.log(id);
      break;
    }
  }
  for (var i = 0; i < array.length; i++) {

    var titleStr = array[i].pid;
    ////console.log(titleStr);
    if (titleStr == id) {
      return true;
    }
  }
  return false;
}

function checkLink(arrayJson) {
  var array = [];
  var arrayJSON = [];
  array = JSON.parse(JSON.stringify(zNodes));

  for (var i = 0; i < array.length; i++) {

    var titleStr = array[i].pid;
    ////console.log(titleStr);
    if (titleStr == id) {
      return true;
    }
  }
  return false;
}

window.onload = function () {
  //  var userid = $.cookie('useridIndexNav');
  //  if (userid == undefined) {
  //      window.location.href = 'login.html';
  //      return;
  //  }
  // $("#username").html($.cookie('userNameIndexNav') + '<span class="layui-nav-more"></span>');
  // console.log(userid);
  $("#treeSerach").hide();
  str = $("#title").text().trim();

  str = str.split(" ");

  var html = "<span>交互式电子技术手册(V4.0)</span>";
  var h1 = "<span id=\"zy\">*点击放大<a href=\"\" target=\"_blank\">请点此处</a></span>";

  $("#help").html(h1);
  $("#xm").addClass("xm");

  diyIcon(zNodes);
  var zTree = $("#tree");
  zTree = $.fn.zTree.init(zTree, setting, zNodes);
  zTree.expandAll(false); //默认节点全部展开

  $('#tree').prepend(`
    <div id="searchDivId">
      <div class="div-input layui-input-inline">
        <input class="layui-input" type="text" id="inputKey" value=""  onkeydown="myFunction()"
          placeholder="请输入索引关键字" />
      </div>
      <button id="search" class="layui-btn layui-btn-normal" style="width: 14%;" onclick="search()">搜索</button>
      <button id="reset" class="layui-btn layui-btn-normal" style="width: 14%;" onclick="reset()">重置</button>
    </div>
  `);


  // 导航栏点击
  $("#nav_box").on("click", "span", function () {
    var htmlName = $(this).data("htmlname");
    console.log("点击的节点名称:", htmlName);

    // 判断当前点击的是否是最后一个span
    var isLastSpan = $(this).is(':last-child');
    var isFirstSpan = $(this).is(':first-child');
    if (isLastSpan || isFirstSpan) {
      console.log("点击的是头尾节点");
    } else {
      console.log("点击的不是最后一个节点");
      // if(htmlName){
      //   $('#myFrame').attr('src', htmlName + '.html');
      // }else{
      //   $('#myFrame').attr('src', '');
      // }
      let node = parentNodes.find(node => node.sid === $(this).data("sid"))
      setting.callback.onClick(null, null, node);
      let dom = document.getElementById(node.tId)
      let doma = document.getElementById(`${node.tId}_a`)
      if (node.htmlName) {
        dom.classList.add('_isDmt');
      } else {
        dom.classList.remove('_isDmt');
      }
      if (doma) {
        $("#tree.ztree a").removeClass("curSelectedNode");
        doma.classList.add('curSelectedNode');
      }
    }
  });
}

function logout() {
  $.removeCookie('useridIndexNav', { path: '/' });
  $.removeCookie('userNameIndexNav', { path: '/' });
  window.location.href = 'login.html';
}

function showHtml(name, reg) {
  //alert("in to showHtml");
  var hurl = baseUrl + name;
  //alert(hurl);
  var patam = {
    name: name
  };
  var u = baseApi + "html/showHtml";
  if (reg) {
    u = baseApi + "html/showHtmlOld";
  }
  $.ajax({
    type: "GET",
    data: patam,
    dataType: "json",
    url: u,
    success: function (r) {
      success(patam, u, r);
      $("#myFrame").attr("src", hurl);
      $("#zy").find("a").attr("href", hurl);

      if (r.data == "no") {
        $("#myFrame").attr("src", "authorization.html");
      }

    },
    error: function (xhr, msg, errorThrown) {
      error(patam, u, xhr, msg, errorThrown);
      $("#myFrame").attr("src", "");
      $("#zy").find("a").attr("href", "");

    }
  });
}

$(function () {
  $(window).resize(function () {
    qofuq();
  });

  function qofuq() {
    var hh = 0;
    hh = $(window).height();
    hh = hh * 0.9
    $("#myFrame").css("height", hh);
    $("#treeSerach").css("height", hh);
    $(".ztree_box").css("height", hh);
  }

  qofuq();


})

function minTree() {
  $("#minDiv").hide();
  $("#maxDiv").show();
  $("#tree").hide();

}
function maxTree() {
  $("#maxDiv").hide();
  $("#minDiv").show();
  $("#tree").show();
}

function setSwf() {

}

function serachAjax(value, arrayJSON) {
  var array = [];
  var patam = {
    value: value
  };
  var u = baseApi + "dxf/checkByValue";
  $.ajax({
    type: "GET",
    data: patam,
    dataType: "json",
    url: u,
    async: false,
    success: function (r) {
      success(patam, u, r);

      array = r.data;
    },
    error: function (xhr, msg, errorThrown) {
      error(patam, u, xhr, msg, errorThrown);
    }
  });
  //console.log(array);
  var array1 = [];
  array1 = JSON.parse(JSON.stringify(zNodes));
  for (var i = 0; i < array.length; i++) {
    var str = array[i].xmlname;
    str = str.split(".")[0] + ".html";
    //console.log(str);
    var flag = true;
    for (var j = 0; j < arrayJSON.length; j++) {
      var linkStr = arrayJSON[j].link;

      if (linkStr == str) {
        flag = false;
      }
    }
    //console.log("flag==" + flag);
    if (flag) {
      for (var k = 0; k < array1.length; k++) {
        var linkStr = array1[k].link;
        if (linkStr == str) {
          //console.log("123131313321123");
          arrayJSON.push(array1[k]);
        }
      }
    }
  }
  return arrayJSON;
}

function serach_b() {
  console.log("in to serach_b");
  var strObj = document.getElementById("serach_text_b");
  var str = strObj.value;
  var array = [];
  var arrayJSON = [];
  array = JSON.parse(JSON.stringify(zNodes));
  console.log(str);
  for (var i = 0; i < array.length; i++) {

    var titleStr = array[i].nodename;
    //console.log(titleStr.indexOf(str));
    if (titleStr.indexOf(str) > -1) {
      arrayJSON.push(array[i]);
    }
  }
  //arrayJSON = serachAjax(str, arrayJSON);
  $("#treeSerach").show();
  $("#tree").hide();
  var zTree = $("#treeSerach");
  //console.log(arrayJSON);
  zTree = $.fn.zTree.init(zTree, setting, arrayJSON);
  zTree.expandAll(true); //默认节点全部展开
  var phtml = `<div id="seachDiv"><input type="text" value="${str}" id="serach_text_b"\>&nbsp;<input type="button" value="搜索" id="serach_b" onclick="serach_b();"\>&nbsp;<input type="button" value="重置" id="allnodes" onclick="allnodes();"\></div><div id="seachDiv_fix"></div>`

  $("#treeSerach").prepend(phtml);

}

function allnodes() {
  $("#tree").show();
  $("#treeSerach").hide();
  document.getElementById("serach_text_b").value = ''
}

$(document).ready(function () {
  if (document.getElementById("nav_box")) {
    document.getElementById("nav_box").innerHTML = `<span class="_span" data-sid="" data-htmlname="">${localStorage.getItem('dataPacketFileName')}</span>`;
  }
})


//回车搜索
function myFunction() {
  if (event.keyCode == 13) {
    search();
  }
}

function search() {
  var content = $("#inputKey").val();
  console.log(content, zNodes);
  if (!content) return;
  let searchList = [];
  zNodes.forEach(item => {
    if (item.htmlName && item.nodename.includes(content)) {
      searchList.push(item)
    }
  })

  var zTree = $("#tree");
  zTree = $.fn.zTree.init(zTree, setting, searchList);
  zTree.expandAll(true); //默认节点全部展开

  $('#tree').prepend(`
    <div id="searchDivId">
      <div class="div-input layui-input-inline">
        <input class="layui-input" type="text" id="inputKey" value=""  onkeydown="myFunction()"
          placeholder="请输入索引关键字" />
      </div>
      <button id="search" class="layui-btn layui-btn-normal" style="width: 14%;" onclick="search()">搜索</button>
      <button id="reset" class="layui-btn layui-btn-normal" style="width: 14%;" onclick="reset()">重置</button>
    </div>
  `);
  if (!searchList.length) {
    $('#tree').append(`
      <div>暂无相关数据</div>
    `);
  }
  $("#inputKey").val(content);
}

function reset() {
  $("#inputKey").val("");
  var zTree = $("#tree");
  zTree = $.fn.zTree.init(zTree, setting, zNodes);
  zTree.expandAll(true); //默认节点全部展开

  $('#tree').prepend(`
    <div id="searchDivId">
      <div class="div-input layui-input-inline">
        <input class="layui-input" type="text" id="inputKey" value=""  onkeydown="myFunction()"
          placeholder="请输入索引关键字" />
      </div>
      <button id="search" class="layui-btn layui-btn-normal" style="width: 14%;" onclick="search()">搜索</button>
      <button id="reset" class="layui-btn layui-btn-normal" style="width: 14%;" onclick="reset()">重置</button>
    </div>
  `);
}

function operation(num) {
  if (num === 1) {
    parent.history.go(1);
  } else {
    parent.history.go(-1); // 后退
  }
}

function shuoding() {
  console.log("锁定页面", $('.shuoding_box'));
  $(parent.document).find('.shuoding_box').css({ 'display': 'flex' });
  let username = localStorage.getItem('username');
  $(parent.document).find('#id_user_name').html(username);
  sessionStorage.setItem('isLocking', 'true');
}
function goHome() {
  // this.$router.push('/');
  parent.location.replace(window.location.origin + '/ietmData/#/home');
  // nginx
  // parent.location.replace(window.location.origin + '/#/home');
}

function history() {
  var dataPacketFileName = localStorage.getItem('dataPacketFileName');
  $.ajax({
    type: "GET",
    url: '/ietm/history/list',
    data: {
      "dataPacketFileName": dataPacketFileName,
      "createBy": localStorage.getItem("username"),
    },
    dataType: "JSON",
    success: function (res) {
      if (res.code == 200) {
        console.log(res, localStorage.getItem("username"));
        var historyList = `
          <div class="title_box">
            <p>历史记录</p><span class="delete_span" id="" onclick="deleteItem('')">清空记录</span>
          </div>`
        historyList += res.data.map(function (item, index) {
          return `
            <a id="tree_${index}_a" class="level" title="${item.dataModuleName}" onclick="historyItemClick('${item.dataModuleFileName}','${item.dataPacketFileName}', '${item.dataModuleName}')">
              <span id="tree_${index}_ico" class="button ico_docu"></span>
              <span id="tree_${index}_span" class="tree_span">${item.dataModuleName}</span>
              <span class="delete_span" id="" onclick="deleteItem('${item.dataModuleFileName}')">删除</span>
            </a>
          `;
        }).join('');
        $(".history #history_list").html(historyList);
        if (!res.data.length) {
          $(".history #history_list").hide();
          layer.msg('暂无历史记录 !');
          return;
        }
        $(".history #history_list").show();
        $(".history #history_list").focus();


      } else {
        if (res.msg.includes("未登录")) {
          layer.msg('用户未登录!');
          setTimeout(function () {
            parent.wlogout()
          }, 1500);
          return false;
        } else {
          layer.msg('请求失败 !');
        }
      }
    }, error: function (res) {
      layer.msg('请求失败 !');
    }
  })
}

function deleteItem(dataModuleFileName) {
  event.stopPropagation();
  console.log(dataModuleFileName);
  var dataPacketFileName = localStorage.getItem('dataPacketFileName');
  function apiF() {
    $.ajax({
      type: "DELETE",
      url: '/ietm/history/delete',
      data: {
        "dataPacketFileName": dataPacketFileName,
        "dataModuleFileName": dataModuleFileName,
        "createBy": createBy,
        "isEmpty": dataModuleFileName ? 0 : 1
      },
      dataType: "JSON",
      success: function (res) {
        if (res.code == 200) {
          layer.msg('删除成功 !');
          var historyList = `
          <div class="title_box">
            <p>历史记录</p><span class="delete_span" id="" onclick="deleteItem('')">清空记录</span>
          </div>`
          historyList += res.data.map(function (item, index) {
            return `
            <a id="tree_${index}_a" class="level" title="${item.dataModuleName}" onclick="historyItemClick('${item.dataModuleFileName}', '${item.dataPacketFileName}', '${item.dataModuleName}')">
              <span id="tree_${index}_ico" class="button ico_docu"></span>
              <span id="tree_${index}_span" class="tree_span">${item.dataModuleName}</span>
              <span class="delete_span" id="" onclick="deleteItem('${item.dataModuleFileName}')">删除</span>
            </a>
          `;
          }).join('');
          $(".history #history_list").html(historyList);
          // $(".history #history_list").show();
          if (!res.data.length) {
            $(".history #history_list").hide();
          }
        } else {
          if (res.msg.includes("未登录")) {
            layer.msg('用户未登录!');
            setTimeout(function () {
              parent.wlogout()
            }, 1500);
            return false;
          } else {
            layer.msg('获取失败 !');
          }
        }
      }, error: function (res) {
        layer.msg('请求失败 !');
      }
    })
  }

  if (dataModuleFileName) {
    apiF();
  } else {
    layer.confirm('确定清空记录吗？', function (index) {
      apiF();
      layer.close(index); // 关闭弹窗
    });
  }
}

function historyItemClick(dataModuleFileName, dataPacketFileName, dataModuleName) {
  localStorage.setItem('dataModuleFileName', dataModuleFileName);
  localStorage.setItem('dataPacketFileName', dataPacketFileName);
  localStorage.setItem('dataModuleName', dataModuleName);
  console.log(path);
  $('#myFrame').attr('src', path + '.html');
  $("#zy").find("a").attr("href", path + '.html');
}

$(document).on('blur', '#history_list', () => {
  console.log('失去焦点: 历史记录列表失去焦点!');
  $(".history #history_list").hide();
});

